package com.dev.weixin.tools.utils.policy;

import java.io.File;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 上传策略
 * @author 飘渺青衣
 * @see
 */
public class UploadRequestPolicy<T> extends GetRequestPolicy<T> {
	
	private Map<String, Object> postParameters;
	
	/**
	 * @param url
	 * @param encoding
	 * @param getParameters
	 * @param postParameters
	 * @param resultClass
	 */
	public UploadRequestPolicy(
			String url, String encoding,
			Map<String, String> getParameters, 
			Map<String, Object> postParameters, 
			Class<T> resultClass) {
		super(url, encoding, getParameters, resultClass);
		this.postParameters = postParameters;
		
	}

	/* (non-Javadoc)
	 * @see com.dev.weixin.tools.utils.policy.RequestPolicy#request(org.apache.http.client.methods.HttpPost, com.fasterxml.jackson.databind.ObjectMapper)
	 */
	@Override
	public void request(HttpPost post, ObjectMapper mapper) {
		MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    	multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    	Iterator<Entry<String, Object>> it = this.postParameters.entrySet().iterator();
    	while(it.hasNext()) {
    		build(multipartEntityBuilder, mapper, it.next());
    	}
    	HttpEntity httpEntity = multipartEntityBuilder.build();
    	post.setEntity(httpEntity);
	}
	
	private void build(MultipartEntityBuilder multipartEntityBuilder, ObjectMapper mapper, Entry<String, Object> entry) {
		String key = entry.getKey();
		Object value = entry.getValue();
		if(value instanceof File) {
			multipartEntityBuilder.addPart(key, new FileBody((File) value));
		} else {
			String other = null;
			if(value instanceof String) {
    			other = (String) value;
			} else {
				try {
    				other = mapper.writeValueAsString(value);
				} catch (UnsupportedCharsetException | JsonProcessingException e) {
					LOG.error(e);
				} 
			}
			LOG.info(other);
			ContentType contentType = ContentType.create("text/plain", this.getEncoding());
			multipartEntityBuilder.addTextBody(key, other, contentType);
		}
	}

}
